import axios from '&helpers/axios';
import React from 'react';
import { getParams } from '&helpers/url';
import { message } from 'antd';
import qs from 'qs'

const API = {
  adminLogin: '/admin/login',
  userLogin:'/user/login',
  adminInfo: '/admin/selectByUsername',
  userInfo: '/user/selectByUsername',
  addUser: '/admin/add'
}

export const STATUS = {
  LOGIN: 'login',
  NOLOGIN: 'nologin'
}

export const models = {
  name: 'user',
  model: {
    state: {
      status: STATUS.NOLOGIN,
      address: "",
      name: "",
      role: "",
      unitName: "",
      username: ""
    },
    reducers: {
      setState(state, payLoad) {
        return {
          ...state,
          ...payLoad
        };
      }
    },
    effects: dispatch => {
      return {
        async adminLogin(params) {
          const { code, data } = await axios.post(API.adminLogin, qs.stringify(params));
          data.status = STATUS.LOGIN;
          // console.log(code);
          // localStorage.setItem('pass-key',data)
          console.log(data);
          code === 0 && await dispatch.user.setState({ ...data }) && message.success('登录成功') && localStorage.setItem('name',data.username) && localStorage.setItem('role','0') 
          code !== 0 &&  message.info('密码错误');
        },
        async updateInfo(params) {
          console.log(params)
        },
        async userLogin(params) {
          const { code, data } = await axios.post(API.userLogin, qs.stringify(params));
          data.status = STATUS.LOGIN;
          // console.log(data);
          // localStorage.setItem('pass-key',data)
          code === 0 && await dispatch.user.setState({ ...data }) && message.success('登录成功') && localStorage.setItem('name',data.username) 
          code !== 0 &&  message.info('密码错误');
        },
        async userInfo(params) {
          const { code, data } = await axios.post(API.userInfo, qs.stringify(params)) 
          code === 0 && await dispatch.user.setState({ ...data }) 
        },
        async adminInfo(params) {
          const { code, data } = await axios.post(API.adminInfo, qs.stringify(params)) 
          code === 0 && await dispatch.user.setState({ ...data }) 
        },
        // async addUser(params) {
        //   const { code, data, msg } = await axios.post(API.addUser, qs.stringify(params))
        //   code === 0 && message.success('添加成功')
        //   code !== 0 && message.error(msg) 
        // }
      }
    }
  }
};
